<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Common\Model;
use Think\Model;
class TradeModel extends Model{
    protected $_validate = array(

    );
    /* 用户模型自动完成 */
    protected $_auto = array(

    );
    protected function order_id(){
        //算出订单ID
        $id = date('Ymd').substr(time(),-5).substr(microtime(),2,2).rand(100,999);
        if($this->where("id={$id}")->count())
            return $this->order_id();
        else
            return $id;
    }
    /*
     * $uid     用户UID
     * $loan_id 贷款ID
     * $title   标题
     * $type    类型（1收入2支出）
     * $paytype 支付类型（0未知，1还款，2续期）  3  缴费
     * $money   金钱
     * $create_time 创建时间
     * $remark 备注
     * $status 状态(0未成功，1已成功)
     *   */
    public function CreateTrade($uid,$loan_id,$title,$type,$paytype,$money,$remark,$status=0){
       /* $info = $this->where("status=0 AND loan_id={$loan_id}")->find();
        if(!empty($info)){
            return $info;
        }*/
        $id=$this->order_id();
        $data = [
            'id'        => $id,
            'uid'       => $uid,
            'loan_id'   => $loan_id,
            'type'      => $type,
            'title'     => $title,
            'paytype'   => $paytype,
            'money'     => $money,
            'create_time' => time(),
            'remark'    => $remark,
            'status'    => $status,
        ];
        $id = $this->add($data);
        //echo $this->getLastSql();exit;
        if($id){
            return $data;
        }else{
            return false;
        }
    }

    //更新交易订单out_trade_no
    public function OutTradeNo($out_trade_no){
        $info = $this->where("id='{$out_trade_no}'")->find();
        $pay_money=$info['money'];
        if($info['status']==0){
            $list = $this->where("id='{$out_trade_no}'")->save(['status'=>1]);



            if($list){
                $vo = M('loan')->where("id='{$info['loan_id']}'")->find();
                $url = U('Capital/loanview?id='.$info['loan_id'],'',true,'weixin.jcsmkj.cn');

                if($info['paytype']==1){   //还款
                    M('loan')->where("id='{$info['loan_id']}'")->save(['status'=>6,'huankuan_time'=>time(),'repay_method'=>2]);//还款
                    $LoanLog =  M('LoanLog');
                    $logData = [
                        'uid'           => $info['uid'],
                        'loan_id'       => $info['loan_id'],
                        'content'       => '',
                        'create_time'   => NOW_TIME,
                        'status'        => 6,
                    ];
                    $LoanLog->add($logData);
                    /**还原额度*/
                    M('Member')->where("uid=".$info['uid'])->setDec('used_money',$vo['money']);
                    //提醒
                    $data = [
                        'title'=>'还款成功',
                        'money'=>$info['money'],
                        'type'=>'还款',
                        'status'=>'成功还款',
                        'mydate'=>date('Y-m-d H:i',$vo['expire_time']),
                        'date'=>date('Y-m-d H:i'),
                        'remark'=>'您已还款成功，感谢您的使用！',
                    ];
                    D('Notice')->weixin(5,$info['uid'],$data,$url);


                    // $yq_day=(strtotime(date("Y-m-d",time()))-strtotime(date("Y-m-d",$vo['expire_time'])))/86400; //逾期天数计算
                    // if($yq_day>0||$yq_day==0){
                    //     $uid=$vo['uid'];
                    //     // $pay_money=0.02*$yq_day*$vo['repayment']+$vo['repayment'];
                    //     $repayment_plan='{"repaymentPlan":[{"date":"'.date("Y-m-d",time()).'","amount":"'.$pay_money.'"}]}';
                    //     $repayment_state=1;
                    //     $repayment_no=$vo['repayment_no'];

                    //     $r=Repaymentplanchange($uid,$repayment_plan,$repayment_state,$repayment_no);
                    //     $r=json_decode($r,true);                        
                    // }   
                    // 发送短信
                    $bank=D('BankCard')->where(array('uid'=>$vo['uid'],'card_number'=>$vo['bank_card']))->find();
                    $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！您已通过支付宝主动还款，已为您恢复额度，可继续使用，客服热线0771-5717965&sendTime=&extno=';
                    $this->send_post($url);
                    








                }elseif($info['paytype']==2){   //延期
                    

                    // $expire_time = strtotime("+{$vo['day']} day",$vo['expire_time']);
                    $m1=0.08*$vo['repayment']; //未到期，延期7天
                    $m2=0.16*$vo['repayment']; //未到期，延期14天
                    $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$vo['expire_time'])))/86400; //逾期天数计算

                    if($yq_day>0){
                        $m3=0.08*$vo['repayment']+0.02*$vo['repayment']*$yq_day; //逾期后延款7天
                        $m4=0.16*$vo['repayment']+0.02*$vo['repayment']*$yq_day; //逾期后延款14天
                    }
                    if($pay_money==$m1){
                        $day=7;
                        $expire_time=$vo['expire_time']+7*86400;

                    }else if($pay_money==$m2){
                        $day=14;
                        $expire_time=$vo['expire_time']+14*86400;
                        
                    }else if(isset($m3)&&$pay_money==$m3){
                        $day=7;
                        $expire_time=time()+7*86400;
                        
                    }else if(isset($m4)&&$pay_money==$m4){
                        $day=14;
                        $expire_time=time()+14*86400;
                       
                    } 
                    //成功之后，记录到期时间
                    M('loan')->where("id='{$info['loan_id']}'")->save(['expire_time'=>$expire_time]);//延长
                    $data = [
                        'day'=>$day,
                        'date'=>date("Y年m月d日",$expire_time),
                        'money'=>$pay_money,
                        'repayment'=>$vo['repayment'],
                        'remark'=>'延期成功',
                    ];
                    D('Notice')->weixin(9,$info['uid'],$data,$url);
                    $bank=D('BankCard')->where(array('uid'=>$vo['uid'],'card_number'=>$vo['bank_card']))->find();
                    $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！延期成功，您已支付'.$money.'元费用延期至'.date("Y年m月d日",$expire_time).'，小西祝您生活愉快！&sendTime=&extno=';
                    $this->send_post($url);

                }else{
                    // 借款前缴费
                    // M('loan')->where("id='{$info['loan_id']}'")->save(['jiaoyi'=>27]);//还款

                    // 手机认证收费
                    $trade=M('trade')->where("id='{$out_trade_no}'")->find();
                    D('MobileMoney')->add(['uid'=>$trade['uid'],'money'=>$pay_money]);



                }
            }

        }
    }


     // /**
    //  * 发送post请求
    //  * @param string $url 请求地址
    //  * @param array $post_data post键值对数据
    //  * @return string
    //  */
    function send_post($url) {
        $post_data = array(
          'username' => 'jkwl362',
          'password' => 'ndp987'
        );
     
      $postdata = http_build_query($post_data);
      $options = array(
        'http' => array(
          'method' => 'POST',
          'header' => 'Content-type:application/x-www-form-urlencoded',
          'content' => $postdata,
          'timeout' => 60 // 超时时间（单位:s）
        )
      );
      $context = stream_context_create($options);
      $result = file_get_contents($url, false, $context);
    }  


}
